package com.mo.modular.auth.filter;

import io.jsonwebtoken.JwtException;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import com.mo.common.exception.BizExceptionEnum;
import com.mo.config.properties.JwtProperties;
import com.mo.core.base.tips.ErrorTip;
import com.mo.core.util.JwtTokenUtil;
import com.mo.core.util.RenderUtil;

/**
 * 对客户端请求的jwt token验证过滤器
 *
 * @author chenxiaodong
 * @Date 2017/8/24 14:04
 */
public class AuthFilter extends OncePerRequestFilter {

	private final Log logger = LogFactory.getLog(this.getClass());

//	@Autowired
//	private JwtTokenUtil JwtTokenUtil;

	@Autowired
	private JwtProperties jwtProperties;

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
			chain.doFilter(request, response);
			return;
		}
		if (request.getServletPath().indexOf("helloGet")>0) {
			chain.doFilter(request, response);
			return;
		}
		if (request.getServletPath().indexOf("show")>0) {
			chain.doFilter(request, response);
			return;
		}
		final String requestHeader = request.getHeader(jwtProperties
				.getHeader());
		String authToken = null;
		if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
			authToken = requestHeader.substring(7);

			// 验证token是否过期
			try {
				boolean flag = JwtTokenUtil.isTokenExpired(authToken,jwtProperties.getSecret());
				if (flag) {
					RenderUtil.renderJson(response, new ErrorTip(
							BizExceptionEnum.TOKEN_EXPIRED.getCode(),
							BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
					return;
				}
			} catch (JwtException e) {
				// 有异常就是token解析失败
				RenderUtil.renderJson(response, new ErrorTip(
						BizExceptionEnum.TOKEN_ERROR.getCode(),
						BizExceptionEnum.TOKEN_ERROR.getMessage()));
				return;
			}
		} else {
			// header没有带Bearer字段
			RenderUtil.renderJson(response, new ErrorTip(
					BizExceptionEnum.TOKEN_ERROR.getCode(),
					BizExceptionEnum.TOKEN_ERROR.getMessage()));
			return;
		}
		chain.doFilter(request, response);
	}
}